package com.sxt.dispatcher;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.sxt.model.LoginAction;

public class MVCDispatcher implements Filter {

	@Override
	public void destroy() {
		System.out.println("控制器销毁");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg2) throws IOException, ServletException {
		System.out.println("传输到达控制器！");

		// 获得用户请求的URL
		String requestURI = ((HttpServletRequest) request).getRequestURI();
		if (requestURI == null || requestURI.isEmpty()) {
			return;
		}

		// 解析URL，得到Action名字
		String actionName = requestURI.substring(
				requestURI.lastIndexOf('/') + 1,
				requestURI.indexOf("action") - 1);

		// 根据名字实例化相应的类
		if (actionName.equals("login")) {
			String userName = request.getParameter("username");
			String passWord = request.getParameter("password");

			// 实例化LoginAction并调用
			LoginAction loginAction = new LoginAction();

			// 用视图从中传来的数据填充业务类的对象
			loginAction.setUserName(userName);
			loginAction.setPassWord(passWord);

			// 得到业务的方法调用结果
			boolean result = loginAction.login();

			// 根据结果跳转到不同的视图
			String skipUrl = null;
			if (result) {
				skipUrl = "list.html";
			} else {
				skipUrl = "invalidUser.html";
			}
			
			request.getRequestDispatcher(skipUrl).forward(request, response);

		} else if (actionName.equals("addUser")) {
			
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("控制器启动");
	}

}
